<?php
class Database_Connector_Read extends Database_Connector_Connective{
    public function __construct(){
        $config = $this->getConfig();
        $options = [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
            PDO::ATTR_PERSISTENT => true

        ];
        parent::__construct(
            $config->slave->dsn,
            $config->slave->user,
            $config->slave->pwd,
            $options
        );

    }


	public function existsTable($table){
		$stmt = $this->prep_query('SHOW TABLES LIKE ?');
		$stmt->execute(array($table));
		return $stmt->rowCount() > 0;
	}

    public function getColumns($table) {
        // $sql = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=\''.$table.'\'' ;
        // $sql = "show columns from $table";
        $sql = 'SHOW COLUMNS FROM '.$table;
        $stmt = $this->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    public function getFields($table){
        // $InstanceCache = Cache::Files();
        // $CachedString = $InstanceCache->getItem($table);
        $cache = Yaf_Registry::get('$table');
        // var_dump($table);
        // if (is_null($CachedString->get())) {
        if(is_null($cache)){
            $sql = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=\''.$table.'\'' ;
            $stmt = $this->prepare($sql);
            $stmt->execute();
            $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $fields = [];
            foreach($columns as $key=>$v ){
                $fields[$key] = $v['COLUMN_NAME'];
            
            }
            Yaf_Registry::set($table,$fields);
            // $CachedString->set(serialize($fields));
            // $InstanceCache->save($CachedString);
            return $fields;
        } else {
            // return unserialize($CachedString->get($table));
            return $cache;
        }
    }
    public function getInfo(){
        $output = array(
            'server' => 'SERVER_INFO',
            'driver' => 'DRIVER_NAME',
            'client' => 'CLIENT_VERSION',
            'version' => 'SERVER_VERSION',
            'connection' => 'CONNECTION_STATUS'
        );
        foreach ($output as $key => $value){
            $output[ $key ] = $this->db->getAttribute(constant('PDO::ATTR_' . $value));
        }
        return $output;
    }

}
